﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Common;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration.UserSecrets;
using Microsoft.Extensions.DependencyInjection;

namespace Extensions.Services.Authorization.Policys;

/// <summary>
/// 权限授权处理器
/// </summary>
public class PermissionHandler:AuthorizationHandler<PermissionRequirement>
{
    private readonly IAuthenticationSchemeProvider _schemes;
    private readonly IHttpContextAccessor _accessor;

    public PermissionHandler(IAuthenticationSchemeProvider schemes, IHttpContextAccessor accessor)
    {
        _schemes = schemes;
        _accessor = accessor;
    }

    // 目前是没有判断的  这边是都给通过的
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
    {
        // httptcontext
        var httpContext = _accessor.HttpContext;

      
        // 获取当前用户所有的  权限   这边坐在本地缓存中吧   本地缓存和可以读取所有的权限
        requirement.Permissions = new List<PermissionItem>();
        

        if (httpContext != null)
        {
            var questUrl = httpContext.Request.Path.Value?.ToLower();

            // 整体结构类似认证中间件UseAuthentication的逻辑，具体查看开源地址
            // https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs
            httpContext.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
            {
                OriginalPath = httpContext.Request.Path,
                OriginalPathBase = httpContext.Request.PathBase
            });

            // Give any IAuthenticationRequestHandler schemes a chance to handle the request
            // 主要作用是: 判断当前是否需要进行远程验证，如果是就进行远程验证
            var handlers = httpContext.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                {
                    context.Fail();
                    return;
                }
            }
            // 表示返回成功
            context.Succeed(requirement);
            //判断请求是否拥有凭据，即有没有登录  鉴权的流程
            // 判断 当前的操作 是都有对应的权限  如果没有  就返回fail
            //var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();
            //if (defaultAuthenticate != null)
            //{
            //    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

            //    // 是否开启测试环境
            //    //var isTestCurrent = Appsettings.app(new string[] { "AppSettings", "UseLoadTest" }).ObjToBool();

            //    //result?.Principal不为空即登录成功
            //    if (result?.Principal != null || isTestCurrent)
            //    {

            //        if (!isTestCurrent) httpContext.User = result.Principal;

            //        // 获取当前用户的角色信息
            //        var currentUserRoles = new List<string>();
            //        // ids4和jwt切换
            //        // ids4

            //            // jwt
            //        currentUserRoles = (from item in httpContext.User.Claims
            //                                where item.Type == requirement.ClaimType
            //                                select item.Value).ToList();


            //        var isMatchRole = false;
            //        var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
            //        foreach (var item in permisssionRoles)
            //        {
            //            try
            //            {
            //                if (Regex.Match(questUrl, item.Url?.ObjToString().ToLower())?.Value == questUrl)
            //                {
            //                    isMatchRole = true;
            //                    break;
            //                }
            //            }
            //            catch (Exception)
            //            {
            //                // ignored
            //            }
            //        }

            //        //验证权限
            //        if (currentUserRoles.Count <= 0 || !isMatchRole)
            //        {
            //            context.Fail();
            //            return;
            //        }

            //        var isExp = false;

            //            // jwt  判断时间  是否超时
            //        isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now;

            //        if (isExp)
            //        {
            //            context.Succeed(requirement);
            //        }
            //        else
            //        {
            //            context.Fail();
            //            return;
            //        }
            //        return;
            //    }
            //}
            ////判断没有登录时，是否访问登录的url,并且是Post请求，并且是form表单提交类型，否则为失败
            //if (!(questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType)))
            //{
            //    context.Fail();
            //    return;
            //}
        }

        //context.Succeed(requirement);
    }
}